package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.appManager.service.IYqdaFilePathSerive;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.manage.domain.ManageFonds;
import cn.yuanqiao.manage.mapper.ManageFondsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;

/**
 * 业务档案门类Service业务层处理
 *
 * @author yuanqiao
 * @date 2023-06-14
 */
@Service
public class TenantCategoryServiceImpl implements ITenantCategoryService
{
    private final Logger logger = LoggerFactory.getLogger(TenantCategoryServiceImpl.class);

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private cn.yuanqiao.archive.appManager.mapper.TenantMdataGroupMapper TenantMdataGroupMapper;
    @Autowired
    private ManageFondsMapper manageFondsMapper;
    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;
    @Autowired
    private InitArchiveMapper initArchiveMapper;
    @Autowired
    private cn.yuanqiao.archive.appManager.mapper.TenantMdataGroupMapper tenantMdataGroupMapper;
    @Autowired
    private YqdaTreesMapper yqdaTreesMapper;
    @Autowired
    private IYqdaFilePathSerive filePathSerive;

    public final static String[] TABLENAMES= {"DATAHEAD","AKBHR","AKBHRXX","AKFZESBKTCPQK","AKFZJBXX","AKFZJYBYXSC","AKFZSAQK",
        "AKFZSJBGQK","AKFZSJQK","AKFZXYR","AKFZYSCPQK","AKSCAJQTYGQK","AKSCBLQK","AKSCCTCPQK","AKSCDPFZYGQK","AKSCJBXX","AKSCQFZSCQQK",
    "AKSCSJQK","AKSCTCKSQK","AKSCTQKSQK","AKSP","AKXS","AKXX","DSRXX","GLNR","GLDZWJGDDJBMLXX","GLGDYJPZMLXX","GLXGSPBMLXX","GLWJSTXX",
    "GLYWGLXX","BKB"};

    /**
     * 查询业务档案门类
     *
     * @param ID 业务档案门类主键
     * @return 业务档案门类
     */
    @Override
    public TenantCategory selectTenanCategoryByID(Long ID)
    {
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(ID,new TenantCategory().getTableName());
        if(tenantCategory !=null){
            tenantCategory.setFilePath(filePathSerive.getFilePath(ID));
        }
        return tenantCategory;
    }
    @Override
    public TenantMdataGroup isBindGroup(Long ID)
    {
        TenantMdataGroup tenantMdataGroup = new TenantMdataGroup();
        String tableName = tenantMdataGroup.getTableName();
        return TenantMdataGroupMapper.selectTenantMdataGroupByID(ID,tableName);
    }

    /**
     * 查询业务档案门类列表
     *
     * @param tenantCategory 业务档案门类
     * @return 业务档案门类
     */
    @Override
    public List<TenantCategory> selectTenantCategoryList(TenantCategory tenantCategory)
    {
        return tenantCategoryMapper.selectTenantCategoryList(tenantCategory);
    }

    /**
     * 新增业务档案门类
     *
     * @param tenantCategory 业务档案门类
     * @return 结果
     */
    @Override
    public int insertTenantCategory(TenantCategory tenantCategory)
    {
        tenantCategory.setCreateTime(DateUtils.getNowDate());
        tenantCategory.setIsDel(0);
        int r = tenantCategoryMapper.insertTenantCategory(tenantCategory);

        //保存电子文件存贮路径
        if(StringUtils.isNotEmpty(tenantCategory.getFilePath())){
            YqdaFilePath filePath = new YqdaFilePath();
            filePath.setCategoryId(tenantCategory.getId());
            filePath.setFilePath(tenantCategory.getFilePath());
            filePathSerive.saveYqdaFilePath(filePath);
        }
        return r;
    }

    /**
     * 修改业务档案门类
     *
     * @param tenantCategory 业务档案门类
     * @return 结果
     */
    @Override
    public int updateTenantCategory(TenantCategory tenantCategory)
    {
        //保存电子文件存贮路径
        if(StringUtils.isNotEmpty(tenantCategory.getFilePath())){
            File file = new File(tenantCategory.getFilePath());
            if(!file.exists()){
                throw new ServiceException("存储位置！文件夹不存在，请先创建文件夹！");
            }
        }
        String filePathStr = filePathSerive.getFilePath(tenantCategory.getId());
        if(filePathStr ==null || !tenantCategory.getFilePath().equals(filePathStr)){
            YqdaFilePath filePath = new YqdaFilePath();
            filePath.setCategoryId(tenantCategory.getId());
            filePath.setFilePath(tenantCategory.getFilePath());
            filePathSerive.saveYqdaFilePath(filePath);
        }
        return tenantCategoryMapper.updateTenantCategory(tenantCategory);
    }

    /**
     * 删除业务档案门类信息
     *
     * @param IDs 业务档案门类主键
     * @return 结果
     */

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteYqdacategoryModelByIDs(Long[] IDs)
    {
        TenantCategory tenantCategory = new TenantCategory();
        for(int j=0;j<IDs.length;j++){
            Long cateId = IDs[j];
            YqdaTrees yqdaTrees = new YqdaTrees();
            yqdaTrees.setCategoryId(cateId);
            List<YqdaTrees> yqdaTrees1 = yqdaTreesMapper.selectYqdaTreesList(yqdaTrees, yqdaTrees.getTableName());
            if(yqdaTrees1.size()!=0){
                throw new ServiceException("该门类已在档案树定义中添加，不可删除！");
            }
        }

        //元数据方案表修改is_use字段
        for(int i=0;i<IDs.length;i++){
            Long cateId = IDs[i];
            String groupId = tenantCategoryMapper.selectGroupIdById(cateId, tenantCategory.getTableName());
            if(StringUtils.isNotEmpty(groupId)){
                TenantMdataGroup group = new TenantMdataGroup();
                group.setIsUse(0);
                group.setId(Long.valueOf(groupId));
                tenantMdataGroupMapper.updateTenantMdataGroup(group);
            }
        }
        return tenantCategoryMapper.deleteYqdacategoryModelByIDs(IDs,tenantCategory.getTableName());
    }

    @Override
    public List<TenantMdataGroup> getNoUseGroups(){
        TenantMdataGroup tenantMdataGroup = new TenantMdataGroup();
        return tenantMdataGroupMapper.selectTenantMdataGroupWithNoUserList(tenantMdataGroup.getTableName());
    }
    /**
     * 获取门类模板树
     * @param yqdacategorymodel
     * @return
     */
    @Override
    public List<TreeSelect> selectmatemodelTreeList(TenantCategory yqdacategorymodel) {
        List<TenantCategory> list = selectTenantCategoryList(yqdacategorymodel);
        String tenantCode = SecurityUtils.getTenantCode();
        List<ManageFonds> manageFonds = manageFondsMapper.selectFondsCodeByTenantCode(tenantCode);
        if(manageFonds==null || manageFonds.size()==0){
            throw new ServiceException("全宗未定义或未启用");
        }
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("档案");
        rootTree.setNodeType("root");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(ManageFonds mf:manageFonds){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(mf.getId());
            chilTree.setLabel(mf.getFondsName());
            chilTree.setFondsCode(mf.getFondsCode());
            chilTree.setTenantCode(mf.getTenantCode());
            chilTree.setNodeType("fonds");
            List<TreeSelect> treeSelects = new ArrayList<>();
            for(TenantCategory catemodel:list){
                if(mf.getFondsCode().equals(catemodel.getFondsCode())){
                    TreeSelect chilTree2 = new TreeSelect();
                    chilTree2.setId(catemodel.getId());
                    chilTree2.setLabel(catemodel.getName());
                    chilTree2.setType(catemodel.getType());
                    chilTree2.setGroupId(catemodel.getGroupId());
                    chilTree2.setOrder_no(catemodel.getOrderNo());
                    chilTree2.setNodeType("cate");
                    treeSelects.add(chilTree2);
                }
            }
            if(treeSelects.size()!=0) chilTree.setChildren(treeSelects);
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }
    /**
     * 获取已定义的树
     * @param yqdacategorymodel
     * @return
     */
    @Override
    public List<TreeSelect> selectTreeList(TenantCategory yqdacategorymodel) {
/*
        List<TenantCategory> list = selectTenantCategoryList(yqdacategorymodel);
*/

        List<TenantCategory> list = tenantCategoryMapper.selectNewTenantCategoryList(yqdacategorymodel);
        String tenantCode = SecurityUtils.getTenantCode();
        List<ManageFonds> manageFonds = manageFondsMapper.selectFondsCodeByTenantCode(tenantCode);
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("档案");
        rootTree.setNodeType("root");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(ManageFonds mf:manageFonds){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(mf.getId());
            chilTree.setLabel(mf.getFondsName());
            chilTree.setFondsCode(mf.getFondsCode());
            chilTree.setTenantCode(mf.getTenantCode());
            chilTree.setNodeType("fonds");
            List<TreeSelect> treeSelects = new ArrayList<>();
            for(TenantCategory catemodel:list){
                if(mf.getFondsCode().equals(catemodel.getFondsCode())){
                    TreeSelect chilTree2 = new TreeSelect();
                    chilTree2.setId(catemodel.getId());
                    chilTree2.setLabel(catemodel.getName());
                    chilTree2.setType(catemodel.getType());
                    chilTree2.setGroupId(catemodel.getGroupId());
                    chilTree2.setOrder_no(catemodel.getOrderNo());
                    chilTree2.setNodeType("cate");
                    treeSelects.add(chilTree2);
                }
            }
            if(treeSelects.size()!=0) chilTree.setChildren(treeSelects);
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int bindgroup(Long id, Long groupid, Integer wjcls, Integer ajcls, Integer xmcls,Integer type) {
        String tenantCode = SecurityUtils.getTenantCode();
        //判断 是修改还是新增
        TenantCategory yqdacategoryModel=new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(id,yqdacategoryModel.getTableName());
        //更新元数据方案信息
        TenantMdataGroup yqdaMdataGroup=new TenantMdataGroup();
        yqdaMdataGroup.setId(groupid);
        yqdaMdataGroup.setWjColLength(wjcls);
        Integer fType = type;
        if(1==type||3==type) yqdaMdataGroup.setAjColLength(ajcls);
        if (3==type) yqdaMdataGroup.setXmColLength(xmcls);
        yqdaMdataGroup.setIsUse(1);
        TenantMdataGroupMapper.updateTenantMdataGroup(yqdaMdataGroup);

        //TenantCategory yqdacategoryModel=new TenantCategory();
        yqdacategoryModel.setId(id);
        yqdacategoryModel.setGroupId(groupid);
        if(!StringUtils.isNotEmpty(groupId)){  //新增
            //更新门类信息
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(id, yqdacategoryModel.getTableName());
            if(type==1 || type==0) type=2;  //件或卷的话 需要添加电子文件表
            for(int i=type;i>=0;i--){
                if(fType==0 && i==1) continue;   //件类型跳过卷
                TenantMdataList tenantMdataList = new TenantMdataList();
                tenantMdataList.setGroupId(groupid);
                tenantMdataList.setType(i);
                List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.selectTenantMdataListList(tenantMdataList);
                Map<String, String> createTableCol = getCreateTableCol(tenantMdataLists);
                String tableName = getTableName(tenantCode, tenantCategory, i);
                tableName = getDisperseTabel(tableName);
                setCategoryTableName(yqdacategoryModel, i, tableName);
                tenantCategoryMapper.createTable(tableName.toUpperCase(), createTableCol, i);  //创建分表
                if (i != 2) {  //电子文件没有总表
                    String mainTableSql = updateMainTableSql(tenantMdataLists, tenantCode, i);//获取更新主表sql
                    if (StringUtils.isNotEmpty(mainTableSql)) {
                        String[] split = mainTableSql.split(";");
                        for (int s = 0; s < split.length; s++) {
                            tenantCategoryMapper.updateMainTableCol(split[s]); //更新主表
                        }
                    }
                }
            }
            //判断是否是检察类 是的话创建相关表
            String storeType = tenantCategory.getStoreType();
            if("j".equalsIgnoreCase(storeType)){
                //先判断检察类的表是否存在
                addJcTable(tenantCode,storeType);
            }
        }
        return tenantCategoryMapper.updateTenantCategory(yqdacategoryModel);
    }

    public void addJcTable(String tenantCode,String storeType){
        int existTable = initArchiveMapper.isExistTable("" + tenantCode+ "_GUIDANGPACKAGE");
        if(existTable==0){
            tenantCategoryMapper.createJCTables(tenantCode,"GUIDANGPACKAGE");
        }
        //String sql = "select COUNT(*) from sysobjects where NAME='"+tenantCode.toUpperCase()+"_GUIDANGPACKAGE'";
        //String single = yqdaarticulatedMapper.getSingle(sql);
        if("j".equalsIgnoreCase(storeType)){
            int existTable2 = initArchiveMapper.isExistTable("" + tenantCode + "_DATAHEAD");
            if(existTable2==0){
                for(String s:TABLENAMES){
                    tenantCategoryMapper.createJCTables(tenantCode,s);
                }
                String insertSql = getInsertSql(tenantCode);
                String[] split = insertSql.split(";");
                for(String s1:split){
                    tenantCategoryMapper.updateMainTableCol(s1);
                }
            }
        }
    }

    //检察类相关表数据
    public String getInsertSql(String tenantCode){
        StringBuilder sb = new StringBuilder();
        sb.append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (1, -1, '案卡信息');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (2, 1, '案件信息');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (3, 1, '犯罪嫌疑人/单位');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (4, 1, '被害人/单位');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (5, 2, '审查起诉案件信息');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (6, 2, '审判活动监督情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (7, 2, '线索移交情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (8, 5, '基本信息');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (9, 5, '侵犯知识产权情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (10, 5, '办理情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (11, 5, '审结情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (12, 5, '案件其他有关情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (13, 5, '毒品犯罪有关情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (14, 5, '出庭裁判情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (15, 5, '提出抗诉情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (16, 5, '提请抗诉情况');")
                .append("insert into \""+tenantCode+"_AKXX\" (\"ID\",\"PARENT_ID\",\"NAME\") values (17, 7, '线索移交情况');")
                .append("insert into \""+tenantCode+"_GLNR\" (\"ID\",\"NAME\",\"CODE\") values (1, '电子文件归档登记表', 'DZWJGDDJB');")
                .append("insert into \""+tenantCode+"_GLNR\" (\"ID\",\"NAME\",\"CODE\") values (2, '归档移交凭证', 'GDYJPZ');")
                .append("insert into \""+tenantCode+"_GLNR\" (\"ID\",\"NAME\",\"CODE\") values (3, '已归档案件修改审批表', 'XGSPB')");
        return sb.toString();
    }

    //表名后缀
    private static String [] suffix = new String []{"A","B","C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private String getDisperseTabel(String initTable){
        String tableName = "";
        //防止表名重复表名后加字母
        for(int i =0;i<26;i++){
            String tableSuffix = (initTable+"_"+suffix[i]).toUpperCase();
            int num = initArchiveMapper.isExistTable(tableSuffix);
            if(num == 0){
                tableName = tableSuffix;
                break;
            }
        }
        return tableName;
    }

    public void setCategoryTableName(TenantCategory yqdacategoryModel, Integer type, String tableName){
        switch (type){
            case 3:
                yqdacategoryModel.setItemTableName(tableName);
                break;
            case 2:
                yqdacategoryModel.setEfileTableName(tableName);
                break;
            case 1:
                yqdacategoryModel.setFolderTableName(tableName);
                break;
            case 0:
                yqdacategoryModel.setFileTableName(tableName);
                break;
            default:
                break;
        }
    }

    public String updateMainTableSql(List<TenantMdataList> tenantMdataLists, String tenantCode, Integer type){
        StringBuffer sb = new StringBuffer();
        String tableName = tenantCode+"_"+(3==type?"YQITEM":1==type?"YQFOLDER":0==type?"YQDA":2==type?"YQDADOCUMENT":"");
        String allFieldOfTable = tenantCategoryMapper.getAllFieldOfTable(tableName.toUpperCase());
        List<String> colList = Arrays.asList(allFieldOfTable.split(","));
        Iterator<TenantMdataList> iterator = tenantMdataLists.iterator();
        while (iterator.hasNext()){
            TenantMdataList next = iterator.next();
            String fieldName = next.getFieldName();
            if(!colList.contains(fieldName)){
                String s = colType(next.getFieldName(), next.getFieldType(), next.getDataLength());
                sb.append("ALTER TABLE ").append(tableName.toUpperCase()).append(" ADD ").append(s).append(";");
            }
        }
        if(sb.length()!=0){
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }

    public String getTableName(String tenantCode, TenantCategory tenantCategory, Integer type){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(tenantCode).append("_")
                .append(tenantCategory.getFondsCode()).append("_")
                    .append(tenantCategory.getCode()).append("_")
                        .append(tenantCategory.getType()).append("_")
                            .append(3==type?"X":1==type?"V":0==type?"F":2==type?"E":"");
        return  stringBuffer.toString();

    }

    public Map<String,String> getCreateTableCol(List<TenantMdataList> tenantMdataLists){
        HashMap<String, String> map = new HashMap<>();
        Iterator<TenantMdataList> iterator = tenantMdataLists.iterator();
        while (iterator.hasNext()){
            TenantMdataList mdl = iterator.next();
            map.put(mdl.getFieldName(),colType(map,mdl.getFieldName(),mdl.getFieldType(),mdl.getDataLength()));
        }
        return map;
    }

    public String colType(String colName,Integer fieldType,Integer dataLength){
        //1=整型,2=字符型,3=日期,4=浮点
        String col ="";
        if(fieldType == 1){
            col = " INT";
        }else if(fieldType == 2){
            col = " VARCHAR("+dataLength*2+")";
        }else if(fieldType == 3){
            col = " VARCHAR(50)";
        }else if(fieldType == 4){
            col = " DOUBLE";
        }else if(fieldType == 5){
            col = " TEXT";
        }else if(fieldType == 6){
            col = " IMAGE";
        }else if(fieldType == 7){
            col = " BIGINT";
        }
        return colName+col;
    }

    private String colType(Map<String,String> data,String colName,Integer fieldType,Integer dataLength){
        String col ="";
        try {
            //1=整型,2=字符型,3=日期,4=浮点
            if(data.get(colName) != null && fieldType == 2){
                //如果字段已存 则已长度最大的为准
                Integer len = Integer.valueOf(data.get(colName).substring(data.get(colName).indexOf("(")+1,data.get(colName).indexOf(")")));
                if(dataLength<len){
                    return data.get(colName);
                }
            }
            if(fieldType == 1){
                col = " INT";
            }else if(fieldType == 2){
                col = " VARCHAR("+dataLength*2+")";
            }else if(fieldType == 3){
                col = " VARCHAR(50)";
            }else if(fieldType == 4){
                col = " DOUBLE";
            }else if(fieldType == 5){
                col = " TEXT";
            }else if(fieldType == 6){
                col = " IMAGE";
            }else if(fieldType == 7){
                col = " BIGINT";
            }
        }catch (Exception e){
            logger.error(colName);
            logger.error(dataLength+"");
            logger.error(data.get(colName));
            logger.error(fieldType+"");
            logger.error(e.getMessage(),e);
            throw new ServiceException("操作失败！");
        }
        return colName+col;
    }

    /*@Override
    public int getNumberByTenantCode(String tenantCode) {
        return tenantCategoryMapper.getNumberByTenantCode(tenantCode,new TenantCategory().getTableName());
    }*/

    @Override
    public List<TenantCategory> getcatebyfondsid(Long fondsid) {
        TenantCategory tenantCategory=new TenantCategory();
        String tenantCode = SecurityUtils.getTenantCode();
        return tenantCategoryMapper.getcatebyfondsid(fondsid,tenantCategory.getTableName(),tenantCode);
    }

    @Override
    public List<TenantCategory> listnopagehasgroup(TenantCategory tenantCategory) {
        return tenantCategoryMapper.listnopagehasgroup(tenantCategory);
    }

    @Override
    public List<TenantCategory> listnopagehasgrouphaspro(Long menuId, Long type) {
        String secSql="";
        Boolean isDagly = SecurityUtils.isDagly();
        if (type == 3) {
            secSql += "and ITEM_TABLE_NAME is not null";
        }
        if (type == 1) {
            secSql += "and FOLDER_TABLE_NAME is not null";
        }
        if(isDagly){

        }else{
            LoginUser user = SecurityUtils.getLoginUser();
            if(user == null){
                user = new LoginUser();
                user.setUserId(1L);
            }
            secSql=" and id in(select a.category_id from "+new YqdaTrees().getTableName() +" a  inner join (select tree_id from "+new YqdaTreesrole().getTableName() +" where role_id in (select role_id from sys_user_role where user_id="+user.getUserId()+") and menu_id="+menuId+") b on a.id=b.tree_id where a.type='a')";
        }
        return tenantCategoryMapper.listnopagehasgrouphaspro(new TenantCategory().getTableName(),secSql);
    }

    @Override
    public void clearTenant(String tenantcode) {
        List<String> tableNameList = initArchiveMapper.getTableListByTenantCode(tenantcode);
        for (String tableName:tableNameList){
            logger.info("drop table = "+tableName);
            initArchiveMapper.dropTable(tableName);
        }
    }

    @Override
    public List<TreeSelect> getcatemodeltreeUse() {
        List<TenantCategory> list = tenantCategoryMapper.getcatemodeltreeUse(new TenantCategory().getTableName());
        String tenantCode = SecurityUtils.getTenantCode();
        List<ManageFonds> manageFonds = manageFondsMapper.selectFondsCodeByTenantCode(tenantCode);
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("档案");
        rootTree.setNodeType("root");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(ManageFonds mf:manageFonds){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(mf.getId());
            chilTree.setLabel(mf.getFondsName());
            chilTree.setFondsCode(mf.getFondsCode());
            chilTree.setTenantCode(mf.getTenantCode());
            chilTree.setNodeType("fonds");
            List<TreeSelect> treeSelects = new ArrayList<>();
            for(TenantCategory catemodel:list){
                if(mf.getFondsCode().equals(catemodel.getFondsCode())){
                    TreeSelect chilTree2 = new TreeSelect();
                    chilTree2.setId(catemodel.getId());
                    chilTree2.setLabel(catemodel.getName());
                    chilTree2.setType(catemodel.getType());
                    chilTree2.setGroupId(catemodel.getGroupId());
                    chilTree2.setOrder_no(catemodel.getOrderNo());
                    chilTree2.setNodeType("cate");
                    treeSelects.add(chilTree2);
                }
            }
            if(treeSelects.size()!=0) chilTree.setChildren(treeSelects);
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }
}
